<template>
	<view>
		<view v-if="showLg||showPhone">
			<view class="mode l-box-pf-t wh100"></view>
			<view v-if="showLg" class="popup c-bg-f c-r-l o-plr">
				<view class="c-tc c-t8 o-ptb u-bb u-c3">微信授权</view>
				<view class="o-plr">
					<view class="c-t7 c-line-20 c-tb o-mt u-bb u-c3">申请获得以下信息</view>
					<view class="c-t6 c-color-b-2 o-pt">
						获得您的公开信息（头像、昵称、地区及性别）
					</view>
				</view>
				<view class="l-box-pa-b w100 o-pb">
					<view class="l-fjb">
						<button size="mini" type="default" @click="refuse">拒绝</button>
						<button size="mini" type="primary" @click="getUserProfile">授权</button>
					</view>
				</view>
			</view>
			<view v-if="showPhone" class="popup c-bg-f c-r-l o-plr">
				<view class="c-tc c-t7 o-pt">
					<view class="c-r50 c-of-h" style="width: 60px;height: 60px;margin: 0 auto 5px;">
						<open-data type="userAvatarUrl"></open-data>
					</view>
					<open-data type="userNickName"></open-data>
				</view>
				<view class="o-plr">
					<view class="c-t6 c-line-20 c-tb u-bb u-c3">申请获得以下信息</view>
					<view class="c-t6 c-color-b-2 o-pt">
						获取您的手机号
					</view>
				</view>
				<view class="l-box-pa-b w100 o-pb">
					<view class="l-fjb">
						<button size="mini" type="default" @click="refuse">拒绝</button>
						<button size="mini" type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import md5 from "@/common/md5.js";
	import WXBizDataCrypt from "@/common/WXBizDataCrypt.js"
	export default {
		name: "authorize",
		data() {
			return {
				code: null,
				phone: null,
				userInfo: {}
			};
		},
		props:{},
		computed:{
			showLg: vm => vm.$store.getters.showLg,
			showPhone: vm => vm.$store.getters.showPhone
		},
		
		mounted() {
			this.getShow();
			if(this.showLg) {
				uni.login({
				  provider: 'weixin',
				  success:(loginRes) => {
					this.code = loginRes.code;
					// this.get_sessionKey()
				  }
				});
			}
		},
		methods: {
			// 获取sessionKey
			get_sessionKey() {
				return new Promise((resolve, reject) => {
					this.$store.dispatch('get_SessionKey', {wxCode: this.code,loading: 'hide'})
					.then(res => {
						if(res.data.code == 200) {
							let session_key = res.data.data.session_key;
							uni.setStorageSync('session_key', session_key);
							resolve(true)
						}else{
							reject(false)
						}
					})
					.catch(err => {
						this.$Function.Toast('sessionKey获取失败');
						reject(false)
					})
				})
				
			},
			//判断是否显示授权
			getShow() {
				this.$store.commit('get_show');
			},
			//拒绝
			refuse() {
				this.refuseTips('拒绝授权，您将无法登录小程序')
			},
			//登陆授权
			async getUserProfile() {
				// #ifdef MP-WEIXIN
				    let a = await this.get_sessionKey();
					console.log('a ==>', a)
					uni.getUserProfile({
						desc: '登录',
						lang:"zh_CN",
						success: (res) => { //这里请求接口
							if(res.errMsg == 'getUserProfile:ok') {
								let userInfo = res.userInfo;
								this.userInfo = userInfo;
								uni.setStorageSync('userInfo', userInfo)
								this.getShow();
							}
						},
						fail: (err) => {
							// console.log(err)
							uni.showToast({
								title: "小程序登录授权失败",
								icon: "none"
							});
						}
					})
				//#endif
			},
			//获取手机号
			getPhoneNumber(e) {
				if(e.detail.errMsg == "getPhoneNumber:ok"){
					let encryptedData = e.detail.encryptedData;
					let errMsg = e.detail.errMsg;
					let iv = e.detail.iv;
					let session_key = uni.getStorageSync('session_key')
				    let pc = new WXBizDataCrypt(this.$url.appId,session_key);
				    let data = pc.decryptData(encryptedData , iv);  
				    // console.log( 'phone ==>' ,data.phoneNumber)       //data就是最终解密的用户信息  
					this.phone = data.phoneNumber;
					uni.setStorageSync('phone', data.phoneNumber);
					this.longin()
				}else if(e.detail.errMsg == "getPhoneNumber:fail no permission") {
					this.$Function.Toast('获取手机号的权限未开通')
					return
				}else{
					// console.log("用户点击了拒绝")
					this.refuseTips('拒绝授权手机号，您将无法登录小程序')
				}   
			},
			
			//登录
			longin() {
				uni.login({
				  provider: 'weixin',
				  success:(loginRes) => {
					  console.log('code ==>',loginRes.code)
					this.interface(loginRes.code)
				  }
				});
				
			},
			
			//登录接口
			interface(e) {
				let opt = {
					tenantId:'000000',
					username:this.phone,
					password:'e10adc3949ba59abbe56e057f20f883e',
					grant_type:'password',
					scope:'all',
					type:'account',
					User_Type: 'weixin',
					WX_Code: e
				}
				this.$store.dispatch('LONGIN', opt).then(res => {
					// console.log('res ==>', res)
					if(res.statusCode == 200) {
						uni.setStorageSync('personalInfo', res.data);
						uni.setStorageSync('token', res.data.access_token);
						uni.setStorageSync('userId', res.data.user_id);
						this.$store.commit('set_userInfo');
						this.$store.commit('set_phone')
						this.$Function.Suc('登录成功');
						this.upUserInfo()
						this.getShow();
						setTimeout(() => {
							this.$emit('showModal', true)
						}, 1000)
						
					}else{
						this.$Function.Toast('小程序登录失败');
					}
				}).catch(err => {console.log('err111 ==>',err)})
			},
			
			//拒绝授权
			refuseTips(e) {
				uni.showModal({
				    title: '提示',
				    content: e,
				    success: (res) => {
				        if (res.confirm) {
				            console.log('用户点击确定');
							this.$store.commit('set_show')
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
			//向后台提交用户信息
			upUserInfo() {
				let userInfo = uni.getStorageSync('userInfo');
				let userId = uni.getStorageSync('userId')
				console.log('userInfo ==>',userInfo)
				this.$store.dispatch('post_modifyNickName', {userId: userId,nickName:userInfo.nickName,loading: 'hide'})
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.mode {
		background: rgba(0, 0, 0, 0.7);
		z-index: 99998;
	}

	.popup {
		position: absolute;
		top: 50%;
		left: 50%;
		width: 280px;
		height: 250px;
		z-index: 99999;
		transform: translate(-140px, -125px);
	}

	button {
		width: 110px;padding: 5px 0;
	}
</style>
